﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Tenancy.Helper;
using System.Data;
using SQLServer.DBUtility;

namespace Tenancy.Server
{
    /// <summary>
    /// Hbung_OrderAlipay 的摘要说明
    /// </summary>
    public class Hbung_OrderAlipay : IHttpHandler
    {
        /// <summary>
        /// 订单支付调用接口
        /// </summary>
        /// <param name="context"></param>

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            
            string HB_Tel = context.Request.Params["Tel"];
            string Hbung_Phone = string.Empty;
            if (string.IsNullOrEmpty(HB_Tel))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Tel为空"));
            }
            else
            {
                string pattern = "^1[0-9]{10}$"; //正则表达式字符串
                Regex cgsregex = new Regex(pattern);
                Hbung_Phone = DESEncrypt.MD5Decrypt(HB_Tel);
                bool isMatch = cgsregex.IsMatch(Hbung_Phone);
                if (!isMatch)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel格式不正确"));
                    return;
                }
            }
            //签名
            string HBsign = context.Request.Params["Sign"];
            if (string.IsNullOrEmpty(HBsign))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Sign为空"));
                return;
            }
            else
            {
                if (GenerClass.IsOkMatch(Hbung_Phone) != Regex.Replace(HBsign, @"\s", "+"))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Sign不匹配"));
                    return;
                }
            }

            string Cpmstr = string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", Hbung_Phone);
            DataTable Mydata = DBHelpSQL.Query(Cpmstr).Tables[0];
            if(Mydata==null||Mydata.Rows.Count==0)
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("用户不存在"));
                return;
            }
          
            //订单编号
            string Hb_OrderNum = context.Request.Params["OrderNum"];
            if(string.IsNullOrEmpty(Hb_OrderNum))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("OrderNum为空"));
                return;
            }
           
            string StrOrder = string.Format("select * from OnlineOrders where CPhone='{0}' and OrderNum='{1}' ", Hbung_Phone, Hb_OrderNum);
            DataTable OrderData=DbLocalSQL.Query(StrOrder).Tables[0];
            if(OrderData==null||OrderData.Rows.Count==0)
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("订单不存在"));
                return;
            }

            string Cgsstrs = string.Format("select * from Hbung_RechargeRecords where rUserTel='{0}' and rOrderNum='{1}' ", Hbung_Phone, Hb_OrderNum);
            DataTable SXMdata = DBHelpSQL.Query(Cgsstrs).Tables[0];
            if(SXMdata!=null&&SXMdata.Rows.Count>0)
            {
                if (SXMdata.Rows[0]["rStatus"].ToString() == "1")
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("已付款"));
                    return;
                }
                else  if (SXMdata.Rows[0]["rStatus"].ToString() == "0")
                {
                    string nurl = "/PayZFB/notify_url.aspx";
                    string strjson = "[{\"notufyUrl\":\"" + nurl + "\",\"tradeNo\":\"" + SXMdata.Rows[0]["tGuID"].ToString() + "\"}]";
                    context.Response.Write(GenerClass.SetSucessJsData("生成支付记录成功", strjson));
                    return;
                }
                else
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("不能付款"));
                    return;
                }
            }
            string strOrderGuid = Guid.NewGuid().ToString(); //付费记录唯一标识
            string RecordsStr = string.Format(@"insert  into Hbung_RechargeRecords (rUserID,rUserName,rUserTel,rCreateTime,
               rDescription,rPay,rStatus,tGuID,rOrderNum,rOrderID) 
               values
              ('{0}','{1}','{2}',getdate(),'{3}','{4}','0','{5}','{6}','{7}')
              ", Mydata.Rows[0]["ID"].ToString(), Mydata.Rows[0]["Name"].ToString(), Hbung_Phone, "利星行租赁订单交易", OrderData.Rows[0]["ExecutoryCost"].ToString(), strOrderGuid,
                OrderData.Rows[0]["OrderNum"].ToString(), OrderData.Rows[0]["ID"].ToString()
                );
            if (DBHelpSQL.ExecuteSql(RecordsStr) > 0)
            {
                string nurl = "/PayZFB/notify_url.aspx";
                string strjson = "[{\"notufyUrl\":\"" + nurl + "\",\"tradeNo\":\"" + strOrderGuid + "\"}]";
                context.Response.Write(GenerClass.SetSucessJsData("生成支付记录成功", strjson));
            }
            else
            {
                context.Response.Write(GenerClass.SetChangeErrorJsData("生成支付记录失败"));
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}